/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml;

import dto.Application;
import dto.ApplicationAccessed;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import util.DateUtil;

/**
 *
 * @author phat10130059
 */
public class XmlFile3 {

    public static List<ApplicationAccessed> readFileXml(String file) {
        List<ApplicationAccessed> list = new ArrayList<ApplicationAccessed>();

        try {

            File fXmlFile = new File(file);

            if (fXmlFile.exists() && !fXmlFile.isDirectory()) {

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);

                //optional, but recommended
                //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
                doc.getDocumentElement().normalize();

                System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

                NodeList nList = doc.getElementsByTagName("App");

                for (int temp = 0; temp < nList.getLength(); temp++) {

                    Node nNode = nList.item(temp);

//                System.out.println("\nCurrent Element :" + nNode.getNodeName());

                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        ApplicationAccessed applicationAccessed = new ApplicationAccessed();

                        Element eElement = (Element) nNode;

                        applicationAccessed.setId(eElement.getAttribute("id"));
                        applicationAccessed.setWindow(eElement.getElementsByTagName("window").item(0).getTextContent());
                        applicationAccessed.setUser(eElement.getElementsByTagName("user").item(0).getTextContent());
                        applicationAccessed.setDate(eElement.getElementsByTagName("date").item(0).getTextContent());
                        applicationAccessed.setHours(eElement.getElementsByTagName("hours").item(0).getTextContent());
                        applicationAccessed.setType(eElement.getElementsByTagName("type").item(0).getTextContent());
                        applicationAccessed.setUrl(eElement.getElementsByTagName("url").item(0).getTextContent());
                        applicationAccessed.setKeyword(eElement.getElementsByTagName("keyword").item(0).getTextContent());
                        applicationAccessed.setImage(eElement.getElementsByTagName("image").item(0).getTextContent());
                        applicationAccessed.setPathProcess(eElement.getElementsByTagName("path").item(0).getTextContent());


                        list.add(applicationAccessed);


                    }
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    public static void createXmlNew(String filePath, ApplicationAccessed applicationAccessed) {
        try {

//            Date d1 = new Date();
//            SimpleDateFormat simpDate = new SimpleDateFormat("yyyyMMddHHmmss");
//            String id = simpDate.format(d1);

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Computer");
            doc.appendChild(rootElement);

            // staff elements
            Element app = doc.createElement("App");
            rootElement.appendChild(app);

            // set attribute to staff element
            Attr attr = doc.createAttribute("id");
            attr.setValue(DateUtil.getDateTimeToString());
            app.setAttributeNode(attr);

            // shorten way
            // staff.setAttribute("id", "1");

            // firstname elements
            Element window = doc.createElement("window");
            window.appendChild(doc.createTextNode(applicationAccessed.getWindow()));
            app.appendChild(window);

            // lastname elements
            Element user = doc.createElement("user");
            user.appendChild(doc.createTextNode(applicationAccessed.getUser()));
            app.appendChild(user);

            // nickname elements
            Element start = doc.createElement("date");
            start.appendChild(doc.createTextNode(DateUtil.getDateToString(new Date())));
            app.appendChild(start);

            // salary elements
            Element end = doc.createElement("hours");
            end.appendChild(doc.createTextNode(DateUtil.getHoursToString(new Date())));
            app.appendChild(end);


            // type elements
            Element type = doc.createElement("type");
            type.appendChild(doc.createTextNode(applicationAccessed.getType()));
            app.appendChild(type);

            // url elements
            Element url = doc.createElement("url");
            url.appendChild(doc.createTextNode(applicationAccessed.getUrl()));
            app.appendChild(url);

            // keyword elements
            Element keyword = doc.createElement("keyword");
            keyword.appendChild(doc.createTextNode(applicationAccessed.getKeyword()));
            app.appendChild(keyword);

            // image elements
            Element image = doc.createElement("image");
            image.appendChild(doc.createTextNode(applicationAccessed.getImage()));
            app.appendChild(image);

            // path elements
            Element path = doc.createElement("path");
            path.appendChild(doc.createTextNode(applicationAccessed.getPathProcess()));
            app.appendChild(path);


            // write the content into xml filePath
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);

            System.out.println("File saved!");

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

    public static void createXmlExist(String filePath, ApplicationAccessed applicationAccessed) {
        try {

            File fXmlFile = new File(filePath);

            if (fXmlFile.exists() && !fXmlFile.isDirectory()) {

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);

                //optional, but recommended
                //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
                doc.getDocumentElement().normalize();

                System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

                Element rootElement = doc.getDocumentElement();

                // staff elements
                Element app = doc.createElement("App");
                rootElement.appendChild(app);

                // set attribute to staff element
                Attr attr = doc.createAttribute("id");
                attr.setValue(DateUtil.getDateTimeToString());
                app.setAttributeNode(attr);

                // firstname elements
                Element window = doc.createElement("window");
                window.appendChild(doc.createTextNode(applicationAccessed.getWindow()));
                app.appendChild(window);

                // lastname elements
                Element user = doc.createElement("user");
                user.appendChild(doc.createTextNode(applicationAccessed.getUser()));
                app.appendChild(user);

                // nickname elements
                Element start = doc.createElement("date");
                start.appendChild(doc.createTextNode(DateUtil.getDateToString(new Date())));
                app.appendChild(start);

                // salary elements
                Element end = doc.createElement("hours");
                end.appendChild(doc.createTextNode(DateUtil.getHoursToString(new Date())));
                app.appendChild(end);

                // type elements
                Element type = doc.createElement("type");
                type.appendChild(doc.createTextNode(applicationAccessed.getType()));
                app.appendChild(type);

                // url elements
                Element url = doc.createElement("url");
                url.appendChild(doc.createTextNode(applicationAccessed.getUrl()));
                app.appendChild(url);

                // keyword elements
                Element keyword = doc.createElement("keyword");
                keyword.appendChild(doc.createTextNode(applicationAccessed.getKeyword()));
                app.appendChild(keyword);

                // image elements
                Element image = doc.createElement("image");
                image.appendChild(doc.createTextNode(applicationAccessed.getImage()));
                app.appendChild(image);

                // path elements
                Element path = doc.createElement("path");
                path.appendChild(doc.createTextNode(applicationAccessed.getPathProcess()));
                app.appendChild(path);

                // write the content into xml filePath
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(filePath));

                // Output to console for testing
                // StreamResult result = new StreamResult(System.out);

                transformer.transform(source, result);

                System.out.println("File saved!");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createXml(String file, List<ApplicationAccessed> list) {

        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Computer");
            doc.appendChild(rootElement);



            for (ApplicationAccessed applicationAccessed : list) {


                // staff elements
                Element app = doc.createElement("App");
                rootElement.appendChild(app);

                // set attribute to staff element
                Attr attr = doc.createAttribute("id");
                attr.setValue(applicationAccessed.getId());
                app.setAttributeNode(attr);

                // shorten way
                // staff.setAttribute("id", "1");

                // firstname elements
                Element window = doc.createElement("window");
                window.appendChild(doc.createTextNode(applicationAccessed.getWindow()));
                app.appendChild(window);

                // lastname elements
                Element user = doc.createElement("user");
                user.appendChild(doc.createTextNode(applicationAccessed.getUser()));
                app.appendChild(user);

                // nickname elements
                Element start = doc.createElement("date");
                start.appendChild(doc.createTextNode(applicationAccessed.getDate()));
                app.appendChild(start);

                // salary elements
                Element end = doc.createElement("hours");
                end.appendChild(doc.createTextNode(applicationAccessed.getHours()));
                app.appendChild(end);


                // type elements
                Element type = doc.createElement("type");
                type.appendChild(doc.createTextNode(applicationAccessed.getType()));
                app.appendChild(type);

                // url elements
                Element url = doc.createElement("url");
                url.appendChild(doc.createTextNode(applicationAccessed.getUrl()));
                app.appendChild(url);

                // keyword elements
                Element keyword = doc.createElement("keyword");
                keyword.appendChild(doc.createTextNode(applicationAccessed.getKeyword()));
                app.appendChild(keyword);

                // image elements
                Element image = doc.createElement("image");
                image.appendChild(doc.createTextNode(applicationAccessed.getImage()));
                app.appendChild(image);

                // path elements
                Element path = doc.createElement("path");
                path.appendChild(doc.createTextNode(applicationAccessed.getPathProcess()));
                app.appendChild(path);
            }



            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(file));

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);

            System.out.println("File saved!");

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

    public static void removeXml(String file, String id) {
        List<ApplicationAccessed> list = readFileXml(file);

        if (list.size() > 0) {
            for (ApplicationAccessed applicationAccessed : list) {
                if (applicationAccessed.getId().equals(id)) {
                    list.remove(applicationAccessed);
                    break;

                }
            }
        }


        System.out.println(list.size());

        createXml(file, list);
    }
    
    public static void removeXml(String file, List<ApplicationAccessed> list) {
        System.out.println(list.size());

        createXml(file, list);
    }

   
}
